package service

import (
	"chat/global"
	"chat/internal/model"
)

func GetUserByPhone(user *model.User) (model.User, error) {
	var queryUser model.User
	err := global.DB.First(&queryUser, "phone = ?", user.Phone).Error
	return queryUser, err
}

func GetUserInfo(id int) (model.User, error) {
	var queryUser model.User
	global.DB.First(&queryUser, "id = ?", id)

	return queryUser, nil
}

func GetLinkedInfoList(uid int) ([]model.User, error) {
	var list []model.User
	err := global.DB.Raw(`SELECT t2.*
FROM users as t0
INNER JOIN user_friends as t1 on t0.id = t1.user_id
INNER JOIN users as t2 ON t1.friend_id = t2.id
WHERE t0.id = ?
union
select distinct u.*
from group_members as t1
inner join group_members as t2 on t1.group_id = t2.group_id
inner join users u on t2.user_id = u.id
where t1.user_id = ?`, uid, uid).Scan(&list).Error
	return list, err
}

func UpdateUserInfo(user model.User) error {
	return global.DB.Exec(`update users
set users.birthday = ?, users.nickname = ?, users.gender = ?, users.intro = ?
where users.id = ?`, user.Birthday, user.Nickname, user.Gender, user.Intro, user.Id).Error
}

func CreateUser(user *model.User) error {
	return global.DB.Create(user).Error
}

func GetUserNumByPhone(phone string) (int, error) {
	r := 0
	err := global.DB.Raw("select COUNT(*)  FROM users WHERE phone = ?", phone).Scan(&r).Error
	return r, err
}

func GetFriendsInfoByUserId(uid int) ([]model.User, error) {
	var list []model.User
	err := global.DB.Raw(`select u.*
from user_friends
inner join users u on user_friends.friend_id = u.id
where user_friends.user_id = ?`, uid).Scan(&list).Error
	return list, err
}

func UpdateAvatarByUid(uid int, avatar string) error {
	return global.DB.Exec("update users set users.avatar = ? where users.id = ?", avatar, uid).Error
}
